package com.cmas.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.manage.domain.CApply;
import com.cmas.manage.domain.CUser;
import com.cmas.manage.mapper.CApplyMapper;
import com.cmas.manage.mapper.CUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.cmas.manage.bo.CommunityAddBo;
import com.cmas.manage.bo.CommunityQueryBo;
import com.cmas.manage.bo.CommunityEditBo;
import com.cmas.manage.domain.Community;
import com.cmas.manage.mapper.CommunityMapper;
import com.cmas.manage.vo.CommunityVo;
import com.cmas.manage.service.ICommunityService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社团Service业务层处理
 *
 * @author cmas
 * @date 2021-05-03
 */
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements ICommunityService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private CApplyMapper cApplyMapper;

    @Autowired
    private CUserMapper cUserMapper;

    @Override
    public CommunityVo queryById(Long id){
        Community db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, CommunityVo.class);
    }

    @Override
    public List<CommunityVo> queryList(CommunityQueryBo bo) {
        LambdaQueryWrapper<Community> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, Community::getDeptId, bo.getDeptId());
        lqw.like(StrUtil.isNotBlank(bo.getCname()), Community::getCname, bo.getCname());
        lqw.eq(StrUtil.isNotBlank(bo.getImgUrl()), Community::getImgUrl, bo.getImgUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduction()), Community::getIntroduction, bo.getIntroduction());
        lqw.eq(bo.getPresidentId() != null, Community::getPresidentId, bo.getPresidentId());
        lqw.eq(StrUtil.isNotBlank(bo.getCstate()), Community::getCstate, bo.getCstate());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<CommunityVo> entity2Vo(Collection<Community> collection) {
        List<CommunityVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CommunityVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Community> page = (Page<Community>)collection;
            Page<CommunityVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(CommunityAddBo bo) {
        Community add = BeanUtil.toBean(bo, Community.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(CommunityEditBo bo) {
        Community update = BeanUtil.toBean(bo, Community.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Community entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<Community> getCommunityByUser(Long userId) {
        return communityMapper.selectList(new QueryWrapper<Community>().eq("president_id",userId));
    }

    @Override
    public List<Community> listVo(Community community) {
        return communityMapper.listVo(community);
    }

    @Override
    public int joinCommunity(CApply cApply) {
        Long communityId = cApply.getCommunityId();
        Long userId = cApply.getUserId();
        CApply cApply1 = cApplyMapper.selectOne(new QueryWrapper<CApply>()
                .eq("community_id", communityId).eq("user_id", userId));
        if (cApply1 != null) {
            if("3".equals(cApply1.getApplyStatus())){
                cApply1.setApplyStatus("1");
                cApplyMapper.updateById(cApply1);
            }
            return 2;
        }
        CUser cUser = cUserMapper.selectOne(new QueryWrapper<CUser>()
                .eq("community_id", communityId).eq("user_id", userId));
        if (cUser != null) {
            return 3;
        }
        return cApplyMapper.insert(cApply);
    }

    @Override
    public List<CApply> getWaitApprovalByUser(Long userId) {
        return communityMapper.selectWaitApprovalByUser(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int agreeJoinCmt(List<Long> idList) {
        List<CApply> cApplyList = cApplyMapper.selectBatchIds(idList);
        for (CApply cApply : cApplyList) {
            cApply.setApplyStatus("2");
            cApplyMapper.updateById(cApply);
            CUser cUser = new CUser().setUserId(cApply.getUserId()).setCommunityId(cApply.getCommunityId());
            cUserMapper.insert(cUser);
        }
        return 1;
    }

    @Override
    public int refuseJoinCmt(List<Long> idList) {
        for (Long id : idList) {
            CApply cApply = new CApply().setApplyStatus("3").setId(id);
            cApplyMapper.updateById(cApply);
        }
        return 1;
    }

    @Override
    public List<CApply> getAgreeByUser(Long userId) {
        return communityMapper.selectAgreeByUser(userId);
    }

    @Override
    public List<CApply> getRefuseByUser(Long userId) {
        return communityMapper.selectRefuseByUser(userId);
    }
}
